package com.cocolove2.library_cocodialog.dialogs.base;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationSet;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cocolove2.library_cocodialog.CornerUtils;
import com.cocolove2.library_cocodialog.TriangleView;
import com.cocolove2.library_cocodialog.animations.BaseAnimatorEffects;

/**
 * 实现PopupWindow风格对话框基类
 * 并支持三角箭头
 * Created by liubo on 8/11/16.
 */
@SuppressWarnings({"unchecked", "unused"})
public abstract class CocoPopBase<T extends CocoPopBase> extends CocoDialogBase<T> {
    protected View mAnchorView;
    protected int[] mAnchorViewLocation = new int[2];
    protected int mGravity = Gravity.BOTTOM;
    protected float mX;
    protected float mY;

    protected float mOffsetX;
    protected float mOffsetY;

    protected int mPopWidth;
    protected int mPopHeight;


    protected View mWrappedView;
    protected TriangleView mTriangleView;
    protected int triangleWidth;
    protected int triangleHeight;

    protected boolean mIsShowTriangle = false;


    public CocoPopBase(Context context) {
        super(context);
        init();
    }

    @SuppressWarnings("unused")
    public CocoPopBase(Context context, int style) {
        super(context, style);
        init();
    }

    private void init() {
        setDimAmount(0.0f);
    }

    /*
    * 这里重写父类执行流程需要自己控制*/
    @Override
    public void onAttachedToWindow() {
        mOnCreateView.post(new Runnable() {
            @Override
            public void run() {
                mPopWidth = mOnCreateView.getWidth();
                mPopHeight = mOnCreateView.getHeight();
                initPopViewLocation(mPopWidth, mPopHeight);
                setupUiView();
                startInAnim();
            }
        });
    }

    /*用于创建pop显示内容布局*/
    protected abstract View onCreatePopView(Context context, ViewGroup parent);

    @Override
    protected View onCreateView(Context context, ViewGroup parent) {
        LinearLayout linearContainer = new LinearLayout(context);
        linearContainer.setOrientation(LinearLayout.VERTICAL);
        linearContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linearContainer.setClickable(true);

        mWrappedView = onCreatePopView(context, linearContainer);

        if (mIsShowTriangle) {
            mTriangleView = new TriangleView(context);
            mTriangleView.setLayoutParams(new RelativeLayout.LayoutParams(triangleWidth, triangleHeight));
            if (mGravity == Gravity.BOTTOM) {
                linearContainer.addView(mTriangleView);
                linearContainer.addView(mWrappedView);
            } else {
                linearContainer.addView(mWrappedView);
                linearContainer.addView(mTriangleView);
            }
        } else {
            linearContainer.addView(mWrappedView);
        }
        return linearContainer;
    }

    @Override
    protected void setupUiView() {
        mWrappedView.setBackground(CornerUtils.cornerDrawable(mDialogBgColor, mCornerRadius));

        /*如何将箭头指向控件中心:
        * 1.view.setX()设置的是相对父布局,而不是屏幕
        * 2.计算方式如下(坐标系是手机屏幕左上角为原点)
        * x=控件的x轴坐标+(控件的宽-箭头的宽)/2-pop对话框的x轴坐标
        * */
        if (mIsShowTriangle) {
            mTriangleView.setColor(mDialogBgColor);
            mTriangleView.setGravity(mGravity == Gravity.TOP ? Gravity.BOTTOM : Gravity.TOP);
            mTriangleView.setX(mAnchorViewLocation[0] + (mAnchorView.getWidth() - mTriangleView.getWidth()) / 2 - mOnCreateView.getX());
        }
    }


    private void initPopViewLocation(int popWidth, int popHeight) {

        mAnchorView.getLocationOnScreen(mAnchorViewLocation);
        if (mGravity == Gravity.BOTTOM) {
            mY = mAnchorViewLocation[1] + mAnchorView.getHeight();
        } else if (mGravity == Gravity.TOP) {
            mY = mAnchorViewLocation[1] - popHeight;
        } else {
            throw new IllegalArgumentException("GravityY must be either Gravity.TOP or Gravity.BOTTOM");
        }

        final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;

        mX = mAnchorViewLocation[0] + (mAnchorView.getWidth() - popWidth) / 2;
        if (mX < 0) {
            mX = mAnchorViewLocation[0];
        } else if (mX + popWidth > screenWidth) {
            mX = mAnchorViewLocation[0] + mAnchorView.getWidth() - popWidth;
        }

        mX = mX - mOffsetX;
        mY = mY - mOffsetY;
        mOnCreateView.setX(mX);
        mOnCreateView.setY(mY);
        /*由于这里是在初始化布局后,设置的动画所以监听要在设置动画后执行*/
        super.setAnimator(getPopInAnimator(), getPopOutAnimator());
        initInListener();
        initOutListener();
    }

    /*使从基类继承来的属性动画设置无效*/
    @SuppressWarnings("unchecked")
    @Override
    public T setAnimator(BaseAnimatorEffects inEffects, BaseAnimatorEffects outEffects) {
        return (T) this;
    }

    /*使从基类继承来的补间动画设置无效*/
    @SuppressWarnings("unchecked")
    @Override
    public T setAnimation(AnimationSet inAnimation, AnimationSet outAnimation) {
        return (T) this;
    }

    /**
     * @param anchorView view
     * @param gravityY   see Gravity#BOTTOM,Gravity#TOP
     * @param offsetX    x轴偏移量 =初始位置-最终位置
     * @param offsetY    y轴偏移量= 初始位置-最终位置
     */
    public void showAsLocation(@NonNull View anchorView, int gravityY, float offsetX, float offsetY) {
        mAnchorView = anchorView;
        mOffsetX = offsetX;
        mOffsetY = offsetY;
        mGravity = gravityY;
        show();
    }

    public void showAsLocation(@NonNull View anchorView, int gravityX, int gravityY) {
        showAsLocation(anchorView, gravityY, 0, 0);
    }

    /**
     * @return pop进入的动画
     */
    protected BaseAnimatorEffects getPopInAnimator() {
        return null;
    }

    /**
     * @return pop退出动画
     */
    protected BaseAnimatorEffects getPopOutAnimator() {
        return null;
    }


    /**
     * 设置三角箭头的宽和高
     */
    public T setTriangleWidthAndHeight(float width, float height) {
        triangleWidth = dp2px(width);
        triangleHeight = dp2px(height);
        return (T) this;
    }

    /**
     * 设置是否显示三角箭头
     */
    public T setShowTriangle(boolean showTriangle) {
        mIsShowTriangle = showTriangle;
        return (T) this;
    }

    /**
     * 内置pop进入动画效果(有反弹效果)
     */
    public class BounceLeftEnter extends BaseAnimatorEffects {
        @Override
        protected void setupAnimator(View view) {
            mAnimatorSet.setDuration(1000).playTogether(ObjectAnimator.ofFloat(view, "alpha", 0, 1, 1, 1),//
                    ObjectAnimator.ofFloat(view, "translationX", -mPopWidth, mX, mX - 20, mX));
        }
    }
    /**
     * 内置pop进入动画效果(无反弹效果)
     */
    public class SlideLeftExit extends BaseAnimatorEffects {
        @Override
        protected void setupAnimator(View view) {
            mAnimatorSet.setDuration(300).playTogether(//
                    ObjectAnimator.ofFloat(view, "translationX", 0, -mPopWidth), //
                    ObjectAnimator.ofFloat(view, "alpha", 1, 0));
        }
    }
    /**
     * 内置pop退出动画效果(无反弹效果)
     */
    public class SlideRightExit extends BaseAnimatorEffects {
        @Override
        protected void setupAnimator(View view) {
            mAnimatorSet.setDuration(300).playTogether(//
                    ObjectAnimator.ofFloat(view, "translationX", 0, mPopWidth), //
                    ObjectAnimator.ofFloat(view, "alpha", 1, 0));
        }
    }
    /**
     * 内置pop退出动画效果(有反弹效果)
     */
    public class BounceRightEnter extends BaseAnimatorEffects {
        @Override
        protected void setupAnimator(View view) {
            mAnimatorSet.setDuration(1000).playTogether(ObjectAnimator.ofFloat(view, "alpha", 0, 1, 1, 1),//
                    ObjectAnimator.ofFloat(view, "translationX", mPopWidth, mX, mX + 20, mX));
        }
    }

}
